﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Timers;

namespace Ashlen.Utility.Mail
{
    public partial class MailService : ServiceBase
    {
        private bool _continueLoop = true;
        private int _waitInterval = 18000;
        private System.Timers.Timer _timer = null;

        public MailService() {
            InitializeComponent();
            _timer = new System.Timers.Timer();
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.Enabled = false;
        }

        void _timer_Elapsed(object sender, ElapsedEventArgs e) {
            try {
                MailUtility.ProcessMailQueue();
            }
            catch (ThreadInterruptedException) { }
            catch (ThreadAbortException) { }
            catch (Exception ex) {
                Log.LogEvent(System.Diagnostics.EventLogEntryType.Error,
                    string.Format("Error occurred in Ashlen Mail service.{0} Details: {1}", System.Environment.NewLine, ex.ToString()));
            }
        }

        public void Start() {
            OnStart(null);
        }

        protected override void OnStart(string[] args) {
            try {
                /* Get the frequency of the service */
                int.TryParse(ConfigurationManager.AppSettings.Get("waitTime"), out _waitInterval);
                Log.LogEvent(System.Diagnostics.EventLogEntryType.Information, "Starting Ashlen Mail Service");

                _timer.Interval = _waitInterval;
                _timer.Enabled = true;
            }
            catch (Exception ex) {
                Log.LogEvent(System.Diagnostics.EventLogEntryType.Error,
                    string.Format("Error occurred in Ashlen Mail service.{0} Details: {1}", System.Environment.NewLine, ex.ToString()));
            }
        }

        protected override void OnStop() {
            Log.LogEvent(System.Diagnostics.EventLogEntryType.Information, "Stopping Ashlen Mail Service");
            _continueLoop = false;
            Thread.CurrentThread.Interrupt();
        }
    }
}
